<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { getClassNameApi, getUserListApi, getCompanyList ,uploadFile} from '@/api/table'
import { ElOption } from 'element-plus'
import { Form } from '@/components/Form'
import { useTable } from '@/hooks/web/useTable'
import { addApi, editApi } from '@/api/login'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { onMounted } from 'vue'
import { useUserStoreWithOut } from '@/store/modules/user'
import { formatToDate, getHourMins, unique } from '@/utils/dateUtil'
const userStore = useUserStoreWithOut()
const ids = ref<string[]>([])
const getClassOption = reactive([])
let userOptions = []
const schema = reactive([])
const schemaFlag = ref(false)
const cid = ref(0)
onMounted(async () => {
  let { data } = await getClassNameApi({ pageIndex: 1, pageSize: 999 })
  for (let i = 0; i < data.list.length; i++) {
    getClassOption.push({
      value: data.list[i].cid,
      label: data.list[i].name
    })
  }
  if (userStore.userInfo.roles === 'teacher') {
    let res = await getUserListApi({ pageIndex: 1, pageSize: 999 }).catch(() => { })
    let list = res.data.list
    for (var i = 0; i < list.length; i++) {
      if (list[i].username.indexOf('teacher') == -1) {
        userOptions.push({
          value: list[i].id,
          label: list[i].nickname
        })
      }
    }
    allSchemas.formSchema.push({
      field: 'mid',
      label: '请选择面试人',
      component: 'Select',
      colProps: {
        span: 24
      },
      componentProps: {
        options: userOptions,
        on: {
          change: (item) => {
            // cid.value = item
            // tableMethods.refresh()
          }
        }
      }
    })
    cid.value = getClassOption[0].value
    schema.push({
      field: 'cid',
      label: '班级',
      component: 'Select',
      componentProps: {
        options: getClassOption,
        on: {
          change: (item) => {
            cid.value = item
            tableMethods.refresh()
          }
        },
        slots: {
          default: (options: SelectOption[]) => {
            if (options.length) {
              return options?.map((v) => {
                return <ElOption key={v.value} label={v.label} value={v.value} />
              })
            } else {
              return null
            }
          },
        }
      }
    })
    schemaFlag.value = true
  }
})
let companyData = []
const companyA = (val) => {
  console.log(val)
  dialogTitle.value = '修改'
  const item = companyData.find(item => item.id === val.id)
  if (item) {
    currentRow.value = item
  }
  dialogVisible.value = true
  actionType.value = ''
}
const { tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getCompanyList({
      cid: cid.value
    })
    companyData = res.data
    for (var i = 0; i < res.data.length; i++) {
      columns.push({
        field: formatToDate(res.data[i].times * 1, 'YYYYMMDD'),
        label: formatToDate(res.data[i].times * 1),
        showOverflowTooltip: false,
        form: {
          hidden: true
        },
        slots: {
          default: (data) => {
            let arr = []
            if (data.row[data.column.property]) {
              arr = data.row[data.column.property]
            }
            return arr.map((val) => {
              return <div onClick={() => { companyA(val) }}>{val?.value}</div>
            })
          }
        }
      })
    }
    columns = unique(columns, 'field').sort((a, b) => {
      return a.field - b.field
    })
    let newArr = []
    for (let i = 0; i < res.data.length; i++) {
      let key = formatToDate(res.data[i].times * 1, 'YYYYMMDD')
      let flag = false
      for (let j = 0; j < newArr.length; j++) {
        if (newArr[j].nickname === res.data[i].nickname) {
          if (!newArr[j][key]) {
            newArr[j][key] = []
          }
          newArr[j][key].push({
            id: res.data[i].id,
            value: res.data[i].company + `(${getHourMins(res.data[i].times * 1, ':')})`
          })
          flag = true
        }
      }
      if (!flag) {
        newArr.push({
          nickname: res.data[i].nickname
        })
        let arr = []
        arr.push({
          id: res.data[i].id,
          value: res.data[i].company + `(${getHourMins(res.data[i].times * 1, ':')})`
        })
        newArr[newArr.length - 1][key] = arr
      }
    }
    return {
      list: newArr
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, currentPage } = tableState
const { getList } = tableMethods
const { t } = useI18n()
let columns = reactive([
  {
    field: 'nickname',
    label: t('user.nickname'),
    fixed: true,
    form: {
      hidden: true
    }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas([])
allSchemas.formSchema.push({
  field: 'company',
  label: '面试公司信息',
  component: 'Input',
  colProps: {
    span: 24
  }
})
allSchemas.formSchema.push({
  field: 'times',
  component: 'DatePicker',
  label: '面试时间',
  colProps: {
    span: 24
  },
  componentProps: {
    type: 'datetime',
    shortcuts: [
      {
        text: t('formDemo.today'),
        value: new Date()
      },
      {
        text: t('formDemo.yesterday'),
        value: () => {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24)
          return date
        }
      },
      {
        text: t('formDemo.aWeekAgo'),
        value: () => {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
          return date
        }
      }
    ]
  }
})
allSchemas.formSchema.push({
  field: 'remark',
  label: '备注',
  component: 'Input',
  colProps: {
    span: 24
  }
})
allSchemas.formSchema.push({
  field: 'callbackmsg',
  component: 'Editor',
  value: '还没开始',
  label: '面试反馈',
  componentProps: {
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: '/zjapi/user/upload',
            headers: { token: userStore.zjToken ?? '' },
            name: 'file',
            fieldName: "file",
            meta: {
              editor: true
            },
          },
          uploadVideo: {
            server: '/zjapi/user/upload',
            headers: { token: userStore.zjToken ?? '' },
            name: 'file',
            fieldName: "file",
            meta: {
              editor: true
            },
          }
        }
      }
    },
  colProps: {
    span: 24
  }
})
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentRow = ref<TableData | null>(null)
const actionType = ref('')
const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
}
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    let res
    if (!formData.id) {
      if (!formData.mid) {
        formData.mid = userStore.userInfo.id
      }
      formData.times = new Date(formData.times).getTime()
      res = await addApi(formData)
        .catch(() => { })
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      res = await editApi(formData)
        .catch(() => { })
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
const fileRef = ref()
const FileAction = () =>{
  // console.log(fileRef.value)
  // 让input file触发点击事件
  fileRef.value.click()
}
const fileChange = () => {
  uploadFile(fileRef.value.files[0]).then(e => {
    console.log(e,294)
  }).catch(error=>{
    console.log(error,296)
  })
  // console.log(formData)
}
</script>

<template>
  <ContentWrap>
    <Form v-if="schemaFlag" :schema="schema" label-width="auto" />
  </ContentWrap>
  <ContentWrap>
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton type="primary" @click="FileAction">文件上传</BaseButton>
      <input type="file" ref="fileRef" @change="fileChange" style="display: none" />
    </div>

    <Table :columns="columns" :data="dataList" :loading="loading" />
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />
    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
